const { query } = require('../../../lib/db');
const { authenticateToken, authorizeRole, hashPassword } = require('../../../lib/auth');
const { validate, registerSchema } = require('../../../lib/validation');

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getUsers(req, res);
      case 'POST':
        return await createUser(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('用户API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取用户列表 - 仅管理员可访问
async function getUsers(req, res) {
  const {
    page = 1,
    limit = 10,
    role,
    department,
    tenant_id,
    keyword
  } = req.query;

  const offset = (parseInt(page) - 1) * parseInt(limit);
  
  // 构建查询条件  
  let whereConditions = [];
  let queryParams = [];
  
  // 添加status条件
  whereConditions.push('u.status = ?');
  queryParams.push(1);

  // 根据用户角色限制数据访问
  if (req.user.role !== 'administrator') {
    whereConditions.push('u.tenant_id = ?');
    queryParams.push(req.user.tenant_id);
  }

  if (role) {
    whereConditions.push('u.role = ?');
    queryParams.push(role);
  }

  if (department) {
    whereConditions.push('u.department = ?');
    queryParams.push(department);
  }

  if (tenant_id && req.user.role === 'administrator') {
    whereConditions.push('u.tenant_id = ?');
    queryParams.push(tenant_id);
  }

  if (keyword) {
    whereConditions.push('(u.name LIKE ? OR u.username LIKE ? OR u.employee_id LIKE ?)');
    const keywordPattern = `%${keyword}%`;
    queryParams.push(keywordPattern, keywordPattern, keywordPattern);
  }

  const whereClause = `WHERE ${whereConditions.join(' AND ')}`;

  // 查询总数 - 临时简化
  const countSql = `
    SELECT COUNT(*) as total 
    FROM users u 
    WHERE u.status = 1
  `;
  const countResult = await query(countSql, []);
  const total = countResult[0].total;

  // 简化查询数据 - 临时修复
  const dataSql = `
    SELECT 
      u.id, u.username, u.name, u.employee_id, u.department, 
      u.email, u.phone, u.role, u.status, u.last_login_at, 
      u.created_at, u.updated_at
    FROM users u
    WHERE u.status = 1
    ORDER BY u.created_at DESC
    LIMIT 10
  `;
  
  const users = await query(dataSql, []);

  res.status(200).json({
    success: true,
    data: {
      users,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / parseInt(limit))
      }
    }
  });
}

// 创建用户 - 仅管理员和操作员可访问
async function createUser(req, res) {
  // 验证请求数据
  const validation = validate(registerSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const userData = validation.data;

  // 检查用户名是否已存在
  const existingUsers = await query(
    'SELECT id FROM users WHERE username = ?',
    [userData.username]
  );

  if (existingUsers.length > 0) {
    return res.status(400).json({
      success: false,
      message: '用户名已存在'
    });
  }

  // 检查邮箱是否已存在
  if (userData.email) {
    const existingEmails = await query(
      'SELECT id FROM users WHERE email = ?',
      [userData.email]
    );

    if (existingEmails.length > 0) {
      return res.status(400).json({
        success: false,
        message: '邮箱已存在'
      });
    }
  }

  // 加密密码
  const hashedPassword = await hashPassword(userData.password);

  // 插入用户数据
  const insertSql = `
    INSERT INTO users (
      username, password, name, employee_id, department, 
      tenant_id, email, phone, role
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const insertParams = [
    userData.username,
    hashedPassword,
    userData.name,
    userData.employee_id || null,
    userData.department || null,
    userData.tenant_id,
    userData.email || null,
    userData.phone || null,
    userData.role
  ];

  const result = await query(insertSql, insertParams);

  // 查询创建的用户详情
  const createdUser = await query(
    `SELECT 
      u.id, u.username, u.name, u.employee_id, u.department, 
      u.email, u.phone, u.role, u.status, u.created_at,
      t.name as tenant_name, t.code as tenant_code
    FROM users u
    LEFT JOIN tenants t ON u.tenant_id = t.id
    WHERE u.id = ?`,
    [result.insertId]
  );

  res.status(201).json({
    success: true,
    message: '用户创建成功',
    data: createdUser[0]
  });
}

export default authorizeRole(['administrator', 'operator'])(handler);